﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace UCF.Core
{
    /// <summary>
    /// 调试侦听器
    /// </summary>
    /// <remarks>2014-6-3 by sutroon</remarks>
    public class MyTraceListener : TraceListener
    {
        /// <summary>
        /// 获取或设置日志目录
        /// </summary>
        public string FolderPath { get; set; }
        public int MaxSize { get; set; }
        private string fileName;
        private string filePath;

        public MyTraceListener(string folderPath)
        {
            FolderPath = folderPath + "\\" + DateTime.Today.Year;
            if (!Directory.Exists(FolderPath)) Directory.CreateDirectory(FolderPath);
            fileName = DateTime.Now.ToString("yyyy-MM-dd-HH");
            MaxSize = 2000000; // 2MB
        }
        private string GetfilePath()
        {
            if (!string.IsNullOrEmpty(filePath) && fileName == DateTime.Now.ToString("yyyy-MM-dd-HH"))
            {
                if (File.Exists(filePath) && File.ReadAllBytes(filePath).Length > MaxSize)
                {
                    fileName = DateTime.Now.ToString("yyyy-MM-dd-HH-mm");
                    filePath = FolderPath + "\\" + fileName + ".log";
                }
                return filePath;
            }
            fileName = DateTime.Now.ToString("yyyy-MM-dd-HH");
            filePath = FolderPath + "\\" + fileName + ".log";
            return filePath;
        }
        private string FormatMessage(string message)
        {
            return string.Format("{0} {1}{2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), message, Environment.NewLine);
        }
        public override void Write(string message)
        {
            GetfilePath();
            File.AppendAllText(filePath, FormatMessage(message));
        }

        public override void WriteLine(string message)
        {
            GetfilePath();
            File.AppendAllText(filePath, FormatMessage(message));
        }

        public override void Write(object o, string category)
        {
            string msg = "";

            if (string.IsNullOrWhiteSpace(category) == false) //category参数不为空
            {
                msg = category + " : ";
            }

            if (o is Exception) //如果参数o是异常类,输出异常消息+堆栈,否则输出o.ToString()
            {
                var ex = (Exception)o;
                msg += ex.Message + Environment.NewLine;
                msg += ex.StackTrace;
            }
            else if (o != null)
            {
                msg = o.ToString();
            }

            WriteLine(msg);
        }
    }
}
